package Multithreading.Thread.ThreadWaitNotify;

import java.util.concurrent.TimeUnit;

public class WaitNotifyDemo {
    public static void main(String[] args) {
        Object locker = new Object();
        int workingSec = 2;
        int threadCount = 5;
        //设置5个线程
        for(int i = 0; i < threadCount; i++){
            new Thread(() -> {
                System.out.println(getName() + "：线程开始工作....");
                synchronized(locker){
                    sleepSec(workingSec);
                    System.out.println(getName() + ":进入等待！！！");

                    try {
                        locker.wait();
                        System.out.println(getName() + ":线程继续.....");
                        sleepSec(2);
                        System.out.println(getName() + "结束");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },"工作线程" + i).start();
        }

        //如果notify/notifyAll在wait之前，会怎么样呢
        System.out.println("--------唤醒线程开始sleep-----------");
        sleepSec(workingSec + 1 );
        System.out.println("--------唤醒线程sleep结束------------");
        synchronized(locker){
//            for(int i = 0; i < threadCount; i++){
//                System.out.println("开始逐个唤醒");
//                locker.notify();
//            }
            locker.notifyAll();
        }

    }


    //睡眠多少秒
    private static void sleepSec(int sec){
        try {
            // SECONDS -> 秒   Millis -> 毫秒
            Thread.sleep(TimeUnit.SECONDS.toMillis(sec));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //获取当前线程的名字
    private static String getName(){
        //currentThread -> 当前线程
        return Thread.currentThread().getName();
    }

}
